import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  TextEditingController _editingController;
  List<String> _messages;
  ScrollController _scrollController;
  bool enableBTN = false;
  @override
  void initState() {
    SystemChrome.setEnabledSystemUIOverlays([]);
    _editingController = TextEditingController();
    _scrollController = ScrollController();
    _messages = List<String>();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blue,
      body: Column(
        children: <Widget>[
          Expanded(
            flex: 9,
            child: ListView.builder(
              controller: _scrollController,
              itemCount: _messages.length ?? 0,
              itemBuilder: (BuildContext context, int index) {
                return index % 2 == 0
                    ? MsgItem(
                        messages: _messages,
                        index: index,
                        isReceive: false,
                      )
                    : MsgItem(
                        messages: _messages,
                        index: index,
                        isReceive: true,
                      );
              },
            ),
          ),
          Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Container(
                  padding: EdgeInsets.all(8.0),
                  child: TextFormField(
                    onChanged: (String text) {
                      setState(() {
                        enableBTN = text.isNotEmpty;
                      });
                    },
                    controller: _editingController,
                  ),
                ),
              ),
              IconButton(
                color: enableBTN ? Colors.cyan : Colors.grey[200],
                icon: Icon(Icons.send),
                onPressed: () {
                  setState(() {
                    final text = _editingController.value.text;
                    if (text.isEmpty || text.length == 0) return;
                    _editingController.clear();
                    _scrollController.animateTo(
                      _scrollController.position.maxScrollExtent,
                      duration: Duration(milliseconds: 200),
                      curve: Curves.easeIn,
                    );
                    _messages.add(text);
                    enableBTN = false;
                  });
                },
              )
            ],
          ),
        ],
      ),
    );
  }
}

class MsgItem extends StatelessWidget {
  MsgItem({
    @required this.messages,
    @required this.index,
    @required this.isReceive,
  });

  final List<String> messages;
  final int index;
  final bool isReceive;
  @override
  Widget build(BuildContext context) {
    final sendItem = <Widget>[
      Spacer(),
      ConstrainedBox(
        child: Container(
          margin: EdgeInsets.all(8.0),
          padding: EdgeInsets.all(8.0),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(32.0),
          ),
          child: Text(
            messages[index],
            textScaleFactor: 1.2,
          ),
        ),
        constraints: BoxConstraints(maxWidth: 200),
      ),
      CircleAvatar(
        backgroundImage: NetworkImage(
            'https://raw.githubusercontent.com/Mr-Cai/Note/master/pic/img/from_avatar.jpg'),
      ),
    ];
    final receiveItem = <Widget>[
      CircleAvatar(
        backgroundImage: NetworkImage(
            'https://raw.githubusercontent.com/Mr-Cai/Note/master/pic/img/to_avatar.jpg'),
      ),
      ConstrainedBox(
        child: Container(
          margin: EdgeInsets.all(8.0),
          padding: EdgeInsets.all(8.0),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(32.0),
          ),
          child: Text(
            messages[index],
            textScaleFactor: 1.2,
          ),
        ),
        constraints: BoxConstraints(maxWidth: 200),
      ),
    ];
    final triangle = CustomPaint(painter: Triangle());
    return Stack(
      children: <Widget>[
        Container(
          margin: EdgeInsets.symmetric(horizontal: 12.0),
          child: Row(
            children: isReceive == true ? receiveItem : sendItem,
          ),
        ),
        isReceive == true
            ? Positioned(left: 66, bottom: 12, child: triangle)
            : Positioned(right: 66, bottom: 12, child: triangle),
      ],
    );
  }
}

class Triangle extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..color = Colors.white;
    final path = Path();
    path.moveTo(10, 0);
    path.lineTo(0, -10);
    path.lineTo(-10, 0);
    path.close();
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}
